<template>
    <div class="app-container">
      <div class="screen-setting">
        <span class="screen-setting-title">分屏设置</span>
        <el-button-group>
          <el-button
            type="primary"
            size="small"
            class="btn"
            :class="{ 'active-btn': screenType == 1 }"
            @click="screenType = 1"
            ><img src="@/assets/icon/video_split_screen_1.png" />单屏</el-button
          >
          <el-button
            type="primary"
            size="small"
            class="btn"
            :class="{ 'active-btn': screenType == 2 }"
            @click="screenType = 2"
            ><img src="@/assets/icon/video_split_screen_2.png" />二分屏</el-button
          >
          <el-button
            type="primary"
            size="small"
            class="btn"
            :class="{ 'active-btn': screenType == 4 }"
            @click="screenType = 4"
            ><img src="@/assets/icon/video_split_screen_4.png" />四分屏</el-button
          >
          <el-button
            type="primary"
            size="small"
            class="btn"
            :class="{ 'active-btn': screenType == 6 }"
            @click="screenType = 6"
            ><img src="@/assets/icon/video_split_screen_6.png" />六分屏</el-button
          >
          <el-button
            type="primary"
            size="small"
            class="btn"
            :class="{ 'active-btn': screenType == 9 }"
            @click="screenType = 9"
            ><img src="@/assets/icon/video_split_screen_9.png" />九分屏</el-button
          >
        </el-button-group>
        <el-button
          type="primary"
          size="small"
          class="btn full-screen"
          @click="fullScreen"
          ><img src="@/assets/icon/video_split_screen_full.png" />全屏</el-button
        >
      </div>
      <div class="layout">
        <div class="left">
          <div class="search_box" v-show="searchBoxShow">
            <ul class="switch_title">
              <li
                :class="{ active: titleActive === index }"
                v-for="(nav, index) in switchList"
                :key="nav"
                @click="switchTitle(index)"
              >
                {{ nav }}
              </li>
            </ul>
            <div class="search_input">
              <input
                type="text"
                v-model="filterText"
                placeholder="区域/设备关键字"
              />
            </div>
            <div class="area_list">
              <vue-scroll :ops="scrollCfg">
                <el-tree
                  ref="treeRef"
                  :data="deptTreeList"
                  node-key="id"
                  :props="defaultProps"
                  :default-expand-all="true"
                  :default-checked-keys="deviceIds"
                  :filter-node-method="filterNode"
                  @node-click="handleNodeClick"
                  show-checkbox
                  @check-change="handleTreeCheckedChange"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <img src="/icon/index_device_manage.png" v-if="data.deptId" />
                    <span>{{ node.label }}</span>
                  </span>
                </el-tree>
              </vue-scroll>
            </div>
          </div>
        </div>
        <div class="center video-show">
          <div
            class="column"
            @click="selectDevice(num)"
            :class="[
              'column-' + screenType,
              activeDeviceIndex === num - 1 ? 'column-active' : '',
            ]"
            v-for="num in screenType"
            :key="num"
            v-show="num <= devices.length"
            v-loading="num <= devices.length && loading"
          >
           <div class="column-title">
              <div class="circular" :class="{'green': num <= devices.length && devices[num - 1].src, 'red': num <= devices.length && !devices[num - 1].src}"></div>
              {{ devices.length - num >= 0 ? devices[num - 1].name : '' }}
            </div>
            <img
            class="close"
              @click.stop="handleCloseVideo(num - 1)"
              src="@/assets/control_close_icon.png"
              alt=""
            />
            <LivePlayer
              v-if="num <= devices.length && !loading"
              :ref="'player' + num"
              :videoUrl="devices[num - 1].src"
              live
            />
            <!-- <LivePlayer
              v-if="num <= devices.length && !loading"
              :ref="'player' + num"
              :videoUrl="devices[num - 1].src"
              :playback-rates =
            /> -->
          </div>
        </div>
        <div class="right">
          <div class="top-container">
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('upleft')"
            >
              <i class="el-icon-arrow-left left-up"></i>
            </div>
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('up')"
            >
              <i class="el-icon-arrow-up"></i>
            </div>
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('upright')"
            >
              <i class="el-icon-arrow-left right-up"></i>
            </div>
            <br />
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('left')"
            >
              <i class="el-icon-arrow-left"></i>
            </div>
  
            <img class="device-img" src="@/assets/control_monitor_icon.png" />
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('right')"
            >
              <i class="el-icon-arrow-right"></i>
            </div>
            <br />
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('left')"
            >
              <i class="el-icon-arrow-left left-down"></i>
            </div>
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('downleft')"
            >
              <i class="el-icon-arrow-down"></i>
            </div>
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('down')"
            >
              <i
                class="el-icon-arrow-left right-down"
                @mousedown.prevent="ptzControl('downright')"
              ></i>
            </div>
          </div>
          <!-- <div class="center-container">
            步长(1-8)
            <el-select placeholder="请选择" v- m class="step-select">
              <el-option v-for="num in 8" :key="num" :label="num" :value="num">
              </el-option>
            </el-select>
          </div> -->
          <div class="bottom-container">
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('zoomout')"
            >
              <i class="el-icon-minus"></i>
            </div>
            <span class="control-title">变倍</span>
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzControl('zoomin')"
            >
              <i class="el-icon-plus"></i>
            </div>
            <br />
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzFiControl('focusfar')"
            >
              <i class="el-icon-minus"></i>
            </div>
            <span class="control-title">变焦</span>
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzFiControl('focusnear')"
            >
              <i class="el-icon-plus"></i>
            </div>
            <br />
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzFiControl('irisout')"
            >
              <i class="el-icon-minus"></i>
            </div>
            <span class="control-title">光圈</span>
            <div
              type="primary"
              circle
              class="btn"
              :class="{ active: activeDeviceIndex >= 0 }"
              @mousedown.prevent="ptzFiControl('irisin')"
            >
              <i class="el-icon-plus"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import {
    fetchDeptTree,
    getDevice,
    handleDeviceControl,
    handleDeviceControlFi,
    getDeviceByDeptIds,
  } from '@/api/deviceManagement.js'
  import Watermark from '@/utils/watermark';
  import { getCookie } from '@/utils/auth';
  import {
    formatTime,
  } from "@/utils/util";
  import { getOnlineStreamUrl } from '@/api/video'
  import LivePlayer from '@liveqing/liveplayer'
  import { getAllChildRenIndex, multArrayToOneArray } from '@/utils/util'
  export default {
    name: 'videoDialog',
    components: {
      LivePlayer,
    },
    data() {
      return {
        fullScreenTag: false, // 全屏
        screenType: 1,
        searchBoxShow: true, //控制视频搜索是否显示
        searchBoxHide: true, //控制视频搜索箭头图标、地图标题位置
        titleActive: 0,
        switchList: [
          '视频直播',
          // "视频回放"
        ],
        scrollCfg: {
          vuescroll: {},
          scrollPanel: {},
          rail: {},
          bar: {
            showDelay: 500,
            onlyShowBarOnScroll: true,
            keepShow: false,
            background: '#0A4696',
            opacity: 1,
            hoverStyle: false,
            specifyBorderRadius: false,
            minSize: 0,
            size: '6px',
            disable: false,
          },
          scrollButton: {
            enable: true,
            background: '#2E72CD',
          },
        },
        deptTreeList: [],
        defaultProps: {
          children: 'children',
          label: 'name',
        },
        activeDeviceIndex: -1,
        devices: [],
        deviceIds: [], // 默认选中设备ID
        filterText: '',
        status: false,
        fiStatus: false,
        loading: true,
        timer: null, // 定时器
        timerOuter: null,
        screenWidth: document.body.clientWidth
  
      }
    },
    watch: {
      filterText(val) {
        this.$refs.treeRef.filter(val)
      },
  
    },
    async mounted() {
      var tips = getCookie('username') + ' (' + formatTime(new Date() / 1000, 'Y-M-D') +  ' )'
          Watermark.set(tips)
          window.addEventListener("resize", this.handleResize);
      this.devices = JSON.parse(this.$route.query.devices)
      this.deviceIds = this.devices.map((item) => {
        return item.id
      })
      this.initScreenType()
      await this.initTree()
      this.initDeviceOnlineUrl();
      (document.onmouseup = () => {
        if (this.status) {
          this.status = false
          this.ptzControl('stop')
        }
        if (this.fiStatus) {
          this.fiStatus = false
          this.ptzFiControl('stop')
        }
      }),
        (this.timer = setInterval(() => {
          console.log('定时刷新')
          this.initDeviceOnlineUrl(false)
        }, 3600000))
    },
    beforeDestroy() {
      this.timer && clearInterval(this.timer)
    },
    methods: {
      handleResize() {
        // 在窗口大小变化时重新添加水印
        var tips = getCookie('username') + ' (' + formatTime(new Date() / 1000, 'Y-M-D') +  ' )'
        Watermark.del(); // 删除原有水印
  
          Watermark.set(tips)
      },
      // 过滤节点
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },
      // 初始化分屏
      initScreenType() {
        let num = this.devices.length
        num > 9 && (num = 9)
        let screenInfo = {
          1: 1,
          2: 2,
          3: 4,
          4: 4,
          5: 6,
          6: 6,
          7: 9,
          8: 9,
          9: 9,
        }
        this.screenType = screenInfo[num]
      },
      // 初始化树
      async initTree() {
        let res = await fetchDeptTree()
        let leafDeptIndexList = getAllChildRenIndex(res.data, 'children')
        let childDeptIds = leafDeptIndexList.map((indexList) => {
          let child = res.data[indexList[0]]
          if (indexList.length === 1) {
            return child.id
          } else {
            for (let i = 1; i < indexList.length; i++) {
              child = child.children[indexList[i]]
            }
            return child.id
          }
        })
        let getDevicesResult = await getDeviceByDeptIds(childDeptIds.join())
        getDevicesResult.data.forEach((item) => {
          let index = this.devices.findIndex((res) => (res.id === item.id))
          if (index >= 0) {
            this.devices[index] = { ...item }
          }
          for (let i = 0; i < leafDeptIndexList.length; i++) {
            let indexList = leafDeptIndexList[i]
            let child = res.data[indexList[0]]
            if (indexList.length === 1 && child.id === item.deptId) {
              child.children.push(item)
              break
            }
            for (let j = 1; j < indexList.length; j++) {
              child = child.children[indexList[j]]
            }
            if (child.id === item.deptId) {
              child.children.push(item)
            }
          }
        })
        this.deptTreeList = res.data
      },
      // 将设备插入树子节点内
      filterArrayAndPush(deptList, deviceList) {
        let depts = []
        depts = deptList.filter((dept) => {
          if (dept.children.length > 0) {
            dept.children = this.filterArrayAndPush(dept.children, deviceList)
          } else {
            dept.children = deviceList.filter((device) => {
              return device.deptId === dept.id
            })
          }
          return dept.children.length > 0
        })
        return depts
      },
      // 获取设备信息
      async initDevicesByIds() {
        try {
          let results = this.devices.map((item) => {
            return getDevice(item.id)
          })
          results = await Promise.all(results)
          this.devices = results.map((result) => {
            return result.data
          })
        } catch (err) {
          console.error('initDevicesByIds', err)
        }
      },
      // 获取在线流播放链接
      async initDeviceOnlineUrl(showLoading = true) {
        try {
          showLoading && (this.loading = true)
          let results = this.devices.map((item) => {
            return getOnlineStreamUrl({
              code: item.channelId,
              serial: item.deviceId,
              _: new Date().getTime(),
            })
          })
          results = await Promise.all(results)
          results.forEach((result, index) => {
            this.devices[index].src = result.WS_FLV
          })
          showLoading && (this.loading = false)
        } catch (err) {
          showLoading && (this.loading = false)
          console.error('getDeviceOnlineUrl', err)
        }
      },
      // 选中设备
      selectDevice(num) {
        this.activeDeviceIndex = num - 1
      },
      ptzControl(val) {
        if (this.activeDeviceIndex < 0) {
          return
        }
        if (val !== 'stop') {
          this.status = true
        }
        const data = {
          command: val,
          id: this.devices[this.activeDeviceIndex].id,
        }
        handleDeviceControl(data)
      },
      ptzFiControl(val) {
        if (this.activeDeviceIndex < 0) {
          return
        }
        if (val !== 'stop') {
          this.fiStatus = true
        }
        const data = {
          command: val,
          id: this.devices[this.activeDeviceIndex].id,
        }
        handleDeviceControlFi(data)
      },
      handleNodeClick(data) {
        if (!data.deptId) {
          return
        }
        let index = this.devices.findIndex((device) => device.id === data.id)
        if (index === this.activeIndex) {
          return
        }
        let activeIndex = this.activeDeviceIndex >= 0 ? this.activeDeviceIndex : 0
        ;[this.devices[activeIndex], this.devices[index]] = [
          this.devices[index],
          this.devices[activeIndex],
        ]
        this.activeDeviceIndex = activeIndex
      },
      fullScreen() {
        this.$fullscreen.enter(this.$el.querySelector(`.video-show`), {
          wrap: false,
          callback: (f) => {
            this.fullScreenTag = f
          },
        })
      },
      // 树节点选中状态改变事件
      handleTreeCheckedChange() {
        this.timerOuter && clearTimeout(this.timerOuter)
        this.timerOuter = setTimeout(async () => {
          let checkedNodes = this.$refs.treeRef.getCheckedNodes()
          if (checkedNodes.length === 0) {
            this.deviceIds = []
            this.devices = []
            this.activeDeviceIndex = -1
            this.initScreenType()
            return
          }
          let depts = multArrayToOneArray(checkedNodes, 'children', false)
          let hash = {}
          depts = depts.reduce((item, next) => {
            hash[next.id] ? '' : (hash[next.id] = true && item.push(next))
            return item
          }, [])
          let devices = depts.filter((item) => {
            return item.deptId
          }) || []
          this.deviceIds = devices.map((item) => {
            return item.id
          })
          this.devices = this.devices.filter(item => {
            return devices.findIndex(res => res.id === item.id) >= 0
          })
          let newDevices = devices.filter(item => {
            let index = this.devices.findIndex(res => res.id === item.id)
            return index < 0
          })
          let results = newDevices.map((item) => {
            return getOnlineStreamUrl({
              code: item.channelId,
              serial: item.deviceId,
              _: new Date().getTime(),
            })
          })
          results = await Promise.all(results)
          results.forEach((result, index) => {
            newDevices[index].src = result.WS_FLV
          })
          this.devices = [...this.devices, ...newDevices]
          this.$forceUpdate()
          this.initScreenType()
        }, 200)
      },
      handleCloseVideo(index) {
        this.$refs.treeRef.setChecked(this.devices[index].id, false)
        this.devices.splice(index, 1)
      },
    },
  }
  </script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style>
  html,
  body,
  #app {
    width: 100%;
    height: 100%;
    min-width: 0vw;
    background: #0d255a;
  }
  </style>
  <style scoped  lang="scss">
  .app-container {
    padding: 0 20px 20px 20px;
    width: calc(100% - 40px);
    height: calc(100% - 106px);
    .screen-setting {
      height: 86px;
      line-height: 86px;
      .screen-setting-title {
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #a3d6ff;
        margin-right: 10px;
      }
      .btn {
        background: #0c265a;
        border: 1px solid #135bb0;
        img {
          width: 12px;
          height: 12px;
          margin-right: 12px;
          vertical-align: bottom;
        }
      }
      // .el-button-group > .el-button {
      //   background: #033b7d;
      //   border: 1px solid #135bb0;
      // }
      .full-screen {
        margin-left: 20px;
      }
      .active-btn {
        background: #033b7d;
      }
    }
    .layout {
      width: 100%;
      height: 100%;
      display: flex;
      .left,
      .center,
      .right {
        height: 100%;
      }
      .left {
        width: 270px;
        .switch_title {
          padding-top: 15px;
          border-bottom: 1px solid #003d95;
          li {
            font-size: 14px;
            font-weight: unset;
            width: 49%;
            height: 30px;
            text-align: center;
            display: inline-block;
            cursor: pointer;
          }
          .active {
            font-weight: bold;
            color: #ffffff;
            background: url('../../assets/switch_title_line.png') no-repeat center
              bottom;
          }
        }
        .search_input {
          padding-top: 10px;
          width: 100%;
          input {
            width: 90%;
            padding: 5px;
            margin-left: 8px;
            text-indent: 25px;
            border-radius: 5px;
            color: #2867a7;
            background: #000033 url('../../assets/map_icon_search.png') no-repeat
              10px center;
            border: 1px solid #003d95;
          }
          input::placeholder {
            color: #2867a7 !important;
          }
        }
        .search_box {
          width: 270px;
          margin: 0px;
          padding: 0px;
          opacity: 0.8;
          height: 100%;
          background: #0a2661;
          .area_list {
            height: calc(100% - 106px);
            margin-top: 20px;
            // overflow: scroll;
            .el-tree {
              background: unset !important;
              color: #afdcff !important;
              & ::v-deep .el-tree-node.is-current > .el-tree-node__content {
                background-color: #113275 !important;
              }
            }
          }
          .submit {
            // margin-left: 10px;
            margin-left: 70px;
            background-repeat: no-repeat;
            background-image: url('../../assets/index_submit.png');
            width: 118px;
            height: 36px;
            background-color: transparent;
            border-style: none;
            cursor: pointer;
          }
          .map_choose {
            margin-left: 10px;
            background-repeat: no-repeat;
            background-image: url('../../assets/index_map_choose.png');
            width: 117px;
            height: 36px;
            background-color: transparent;
            border-style: none;
          }
        }
      }
      .center {
        margin-left: 24px;
        width: calc(100% - 534px);
        // display: flex;
        // justify-content: center;
        // align-content: center;
        // flex-wrap: wrap;
        height: auto;
        overflow-y: auto;
        // align-content: flex-start;
        .column {
          margin: 0;
          border: 2px solid #07193d;
          background: red;
          height: 0;
          float: left;
          position: relative;
          .column-title {
            position: absolute;
            font-size: 12px;
            font-family: Microsoft YaHei;
            font-weight: bold;
            color: #ffffff;
            z-index: 999;
            left: 6px;
            top: 6px;
            .circular {
              width: 4px;
              height: 4px;
              border-radius: 50%;
              display: inline-block;
              vertical-align: middle;
            }
            .red {
              background: red;
            }
            .green {
              background: green;
            }
          }
          .close {
            position: absolute;
            right: 0px;
            top: 0px;
            width: 25px;
            height: 25px;
            cursor: pointer;
            z-index: 999;
          }
        }
        .column-active {
          border: 2px solid #3b98ff;
        }
        .column-1 {
          width: calc(100% - 4px);
          background: #0c265a;
          padding-bottom: 56%;
        }
        .column-2 {
          width: calc(50% - 4px);
          background: #0c265a;
          padding-bottom: 28%;
        }
        .column-4 {
          width: calc(50% - 4px);
          background: #0c265a;
          padding-bottom: 28%;
        }
        .column-6 {
          width: calc(100% / 3 - 4px);
          background: #0c265a;
          padding-bottom: 18.667%;
        }
        .column-9 {
          width: calc(100% / 3 - 4px);
          background: #0c265a;
          padding-bottom: 18.667%;
        }
        .dummy {
          height: 1px;
          visibility: hidden;
        }
      }
      .right {
        width: 235px;
        .top-container,
        .bottom-container {
          text-align: center;
          .btn {
            background: #033b7d;
            border: 1px solid #135bb0;
            margin-left: 16px;
            margin-bottom: 17px;
            width: 42px;
            height: 42px;
            color: #1b488b;
            font-size: 18px;
            font-weight: bold;
            display: inline-block;
            border-radius: 50%;
            text-align: center;
            line-height: 42px;
            cursor: pointer;
          }
          .device-img {
            width: 25px;
            height: 29px;
            vertical-align: middle;
            margin-left: 25.5px;
            margin-right: 8.5px;
          }
          .active {
            color: #3b98ff;
          }
          .left-up {
            transform: rotate(45deg);
          }
          .right-up {
            transform: rotate(135deg);
          }
          .left-down {
            transform: rotate(-45deg);
          }
          .right-down {
            transform: rotate(-135deg);
          }
          .control-title {
            display: inline-block;
            width: 42px;
            text-align: center;
            margin-left: 16px;
          }
        }
        .center-container {
          margin: 8px 0 24px 0;
          text-align: center;
          .step-select {
            text-align: center;
            width: 84px;
          }
        }
      }
    }
  }
  .custom-tree-node {
    font-size: 14px;
    img {
      width: 12px;
      height: 12px;
      margin-right: 10px;
    }
  }
  ::v-deep .el-loading-mask {
    background-color: rgba(0, 0, 0, 0.5);
  }
  </style>